from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
import pymysql

pymysql.install_as_MySQLdb()

# 加载环境变量
load_dotenv()

# 数据库配置
DATABASE_URL = os.getenv(
    "DATABASE_URL", "mysql+pymysql://user:password@localhost/teahouse"
)

# 创建SQLAlchemy引擎
engine = create_engine(DATABASE_URL)

# 创建数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# 创建所有表
def create_tables():
    from main import metadata

    metadata.create_all(bind=engine)


# 关闭数据库连接
def close_db():
    engine.dispose()
